<?php 
class Application_Helper_Mail
{
	private static $_instance = null;
	
	private $_server = '';
	private $_port = '';
	private $_username = '';
	private $_password = '';
	private $_tls = false;
	
	public function connect($server, $port, $username, $password, $tls = false)
	{
		$this->_server = $server;
		$this->_port = $port;
		$this->_username = base64_encode($username);
		$this->_password = base64_encode($password);
		$this->_tls = $tls;
	}
	
	public static function getInstance()
	{
		if(self::$_instance == null)
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	public static function send($from, $to, $replyTo, $title, $body)
	{
		$instance = self::getInstance();
		
		return $instance->_send($from, $to, $replyTo, $title, $body);
	}
	
	private function _send($from, $to, $replyTo, $title, $body)
	{
		$result = array();
		
		if ($client = fsockopen ($this->_server, $this->_port))
		{
			fputs ($client, "EHLO {$this->_server}\r\n");
			$talk['hello'] = fgets ($client, 1024);
			
			fputs($client, "auth login\r\n");
			$talk['res'] = fgets($client, 1024);
			
			fputs($client, "{$this->_username}\r\n");
			$talk['user'] = fgets($client, 1024);
			
			fputs($client, "{$this->_password}\r\n");
			$talk['pass'] = fgets($client, 256);
			
			if($this->_tls)
			{
				fputs($client, "STARTTLS\r\n");
				if(! stream_socket_enable_crypto($client, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) 
				{
					return false;
				}
			}
			
			fputs ($client, "MAIL FROM: <{$from}>\r\n");
			$talk['From'] = fgets($client, 1024);
			
			fputs ($client, "RCPT TO: <{$to}>\r\n");
			$talk['To'] = fgets($client, 1024);
			
			fputs($client, "DATA\r\n");
			$talk['data'] = fgets($client, 1024);
			fputs($client, "To: <{$replyTo}>\r\nFrom: <{$from}>\r\nSubject:{$title}\r\n\r\n\r\n{$body}\r\n.\r\n");
			$talk['send'] = fgets($client, 256);
			fputs ($client, "QUIT\r\n");
			fclose($client);
		}
		
		return $result;
	}
}